import React, { Component } from 'react';
import { Button, Table, Tree, Modal, Form, Input, Select, Drawer, Space, message } from 'antd';
import { MinusCircleOutlined } from '@ant-design/icons'
import style from './style.module.scss'
import { routes } from '../../router';
import toExcel from '../../utils/toExcal';
import Login from '../../api/Login';
import md5 from "md5";

const secret = '123jiasW';
const { Option } = Select;

const { userBox, formItem } = style
class Index extends Component {
    //   const [tel, setTel] = useState("0")

    state = {
        userList: [],
        open: false,
        addopen: false,
        adduserList: [{
            tel: '',
            password: '',
            checkedKeys: [],
            adminid: Date.now(),
            token: Date.now().toString(16),
            id: Date.now().toString(8),
        }],
        user: {},
        tel: '',
        checkedKeys: [],
        checkbox: [],
        changedpassword: ''
    }
    getUserList = async () => {
        let res = await Login['getadminlist']()
        console.log(res);
        console.log(res.data.data, 'use');
        this.setState({
            userList: res.data.data
        })
    }
    componentDidMount() {
        const box = []
        console.log(routes, 'rou');
        for (let a = 0; a < routes.length; a++) {
            box.push(routes[a].title)
            if (routes[a].children) {
                box.push(routes[a].children[0].title)
            }
        }
        this.setState({
            checkbox: box
        })
        this.getUserList()

        // console.log(JSON.parse(JSON.parse(sessionStorage.getItem("persist:storeReudx")).user).adminid)

    }
    handleOk = async (id, password,oldpassword) => {
        console.log(id, password, "666");
        this.setState({
            open: !this.state.open
        })
        console.log(password,oldpassword,"mima");
        if (password !== ""&& md5(password+secret) !==oldpassword ) {
            let res = await Login["changepassword"]({ id, password })
            console.log(res);
            if (res.code === 200) {
                message.success({
                    content: res.data.message
                })
            }
        }
        else{
            message.error({
                content: "密码不能空白或者与旧密码相同"
            })
        }
    }
    handleCancel = () => {
        this.setState({
            open: false,
        })
    }

    userHandler = (row) => {
        this.setState({
            open: true,
            user: row,
        })
    }
    onSearch = (val) => {
        // console.log(val, 'val');
        this.setState({
            userList: this.state.userList.filter(item => item.adminname.includes(val))
        })
    }
    showDrawer = () => {
        this.setState({
            adduserList: [...this.state.adduserList],
            addopen: true

        })
    }
    onClose = () => {
        this.setState({
            addopen: false

        })
    }
    Dela = async (id) => {
        let res = await Login["deladmin"](id)
        console.log(res);
        message.success({
            content: res.data.message
        })
        this.getUserList()
    }

    del = (key) => {
        this.setState({
            adduserList: this.state.adduserList.filter(item => item.key !== key)
        })
    }
    changeInput = (key, e) => {
        let { name, value } = e.target
        console.log(name, value);
        this.setState({
            adduserList: this.state.adduserList.map(item => {
                if (item.key === key) {
                    item[name] = value
                }
                return item
            })

        })
    }
    onOk = async () => {
        console.log(this.state.adduserList);
        let res = await Login["register"](this.state.adduserList[0])
        console.log(res.code, res.data.data, res.data.message);
        if (res.code === 200) {
            let res = await Login["doRegister"](this.state.adduserList[0])
            console.log(res);
            if (res.code === 200) {
                message.success({
                    content: res.data.message
                })
                this.getUserList()
            }
        }
        else {
            message.error({
                content: res.data.message
            })
        }
        this.setState({
            addopen: false
        })
    }
    handleChange = (value) => {
        console.log(value);
        this.setState({
            checkedKeys: value
        })
    };
    changecheckkeys = async (id) => {
        console.log(this.state.checkedKeys, "xiugai");
        let res = await Login["changePermissions"]({ id, checkedKeys: this.state.checkedKeys })
        console.log(res, res.code);
        if (res.code === 200) {
            message.success({
                content: res.data.message
            })
            this.getUserList()
        }
    }

    saveExcel = () => {
        let datas = [
            {
                //第一个sheet
                sheetData: this.state.userList.map((item, index) => {
                    item.checkedKeys = item.checkedKeys
                    item.index = index + 1
                    return item
                }),
                sheetName: '管理员',
                sheetFilter: ['index', 'adminname', 'tel', "checkedKeys", "password"],
                sheetHeader: ['序号', '用户名', '电话号码', "可访问权限", "密码"]
            },
        ]
        toExcel('用户excel', datas)
    }
    onCheck = (key, v, v1) => {
        console.log(key, v, v1, 'check');
        let keys = [...v, ...v1.halfCheckedKeys]
        this.setState({
            adduserList: this.state.adduserList.map(item => {
                if (item.key == key) {
                    item.checkedKeys = keys
                }
                return item
            })
        })
    }
    tochangepassword = (e) => {
        console.log(e.target.value, "value");
        this.setState({
            changedpassword: e.target.value
        })
    }
    render() {
        const { tel, userList, open, addopen, adduserList, user, changedpassword } = this.state
        const columns = [
            {
                title: '序号',
                render: (_, row, index) => <span>{index + 1}</span>
            },
            {
                width: 200,
                title: '用户名',
                render: (_, row, index) => <span>{row.adminname}</span>
            },
            {
                width: 200,
                title: '电话号码',
                render: (_, row, index) => <span>{row.tel}</span>
            },
            {
                title: '可访问权限',
                render: (_, row, index) => <Select
                    mode="multiple"
                    // style={{ width: '100%' }}
                    placeholder="请选择权限"
                    defaultValue={row.checkedKeys}
                    onChange={this.handleChange}
                    onBlur={() => { this.changecheckkeys(row.id) }}
                    optionLabelProp="label"
                    style={{ width: 400 }}
                >
                    {
                        this.state.checkbox.map(item => <Option value={item} label={item}>
                            <Space>
                                {item}
                            </Space>
                        </Option>)
                    }
                </Select>
            },
            {
                title: '操作',
                render: (_, row, index) =>
                    <>
                        <Button onClick={() => this.userHandler(row)} style={{ marginRight: 20 }}>修改密码</Button>
                        <Button onClick={() => this.Dela(row.id)}>删除</Button>
                    </>
            },
        ]

        return (
            <div className={userBox}>
                <div style={{ padding: "20px 0", display: "flex" }}>
                    <Button onClick={this.showDrawer}>添加</Button> <Input.Search onChange={(e) => {
                        if (e.target.value === '') {
                            this.getUserList()
                        }
                    }} onSearch={this.onSearch} enterButton />
                    <Button onClick={this.saveExcel}>导出表格</Button>
                </div>

                <Table rowKey='adminid' columns={columns} dataSource={userList} />

                <Modal title="修改密码（修改前先删除加密过的密码）" open={open} onOk={() => { this.handleOk(user.id, changedpassword ,user.password) }} onCancel={this.handleCancel} >
                    <Form
                        ref={node => this.form = node}
                        key={user.adminid}
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600 }}
                        initialValues={user}
                        onFinish={this.onFinish}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="用户名"
                            name="adminname"
                            rules={[{ required: true, message: '请输入手机号' }]}
                        >
                            <Input disabled />
                        </Form.Item>
                        <Form.Item
                            label="密码"
                            name="password"
                            defaultValue={user.password}
                            rules={[{ required: true, message: '请输入密码' }]}
                        >
                            <Input defaultValue={123456} onChange={(e) => { this.tochangepassword(e) }} />
                        </Form.Item>
                    </Form>
                </Modal>
                <Drawer
                    title="添加用户"
                    width={500}
                    onClose={this.onClose}
                    open={addopen}
                    extra={
                        <Space>
                            <Button onClick={this.onClose}>取消添加</Button>

                            <Button type="primary" onClick={this.onOk}>
                                确认添加
                            </Button>
                        </Space>
                    }
                >
                    {
                        adduserList.map(item => <div key={item.key} className={formItem}>
                            <Input name='adminname' onChange={(e) => this.changeInput(item.key, e)} placeholder='用户名' value={item.adminname}></Input>
                            <Input name='tel' onChange={(e) => this.changeInput(item.key, e)} placeholder='手机号' value={item.tel}></Input>
                            <Input name='password' onChange={(e) => this.changeInput(item.key, e)} placeholder='密码' value={item.password}></Input>
                            <Tree
                                checkable
                                fieldNames={{ title: "title", key: 'title' }}
                                // onSelect={(v, v1) => this.onSelect(item.key, v, v1)}
                                onCheck={(v, v1) => this.onCheck(item.key, v, v1)}
                                treeData={routes}
                            />
                            <MinusCircleOutlined onClick={() => this.del(item.key)} style={{ marginRight: 20 }} size={30} />

                        </div>)
                    }
                    {/* <PlusCircleOutlined onClick={this.addbtn} /> */}

                </Drawer>
            </div>
        );
    }
}

export default Index;
